import { ref, watch, onMounted } from 'vue'

const languageType = ref('English')

export function useLanguage() {
	const setLanguage = (lang : string) => {
		languageType.value = lang
		if (process.client) { // ✅ 只在浏览器中执行
			localStorage.setItem('languageType', lang)
		}
	}

	// ✅ 初始化时从 localStorage 读取
	onMounted(() => {
		if (process.client) {
			const savedLang = localStorage.getItem('languageType')
			if (savedLang) {
				languageType.value = savedLang
			}
		}
	})

	// ✅ 同步多标签页
	if (process.client) {
		window.addEventListener('storage', (e) => {
			if (e.key === 'languageType' && e.newValue) {
				languageType.value = e.newValue
			}
		})
	}

	return {
		languageType,
		setLanguage
	}
}